#include "gamepanelbutton.h"

GamePanelButton::GamePanelButton(const QPixmap & pixmap, QGraphicsItem * parent) :
            QGraphicsWidget(parent),
            m_pixmap(pixmap),
            m_hovered(false),
            m_isToggled(false),
            m_canToggle(false)
{
    setAcceptsHoverEvents(true);
    setCacheMode(DeviceCoordinateCache);
    setMinimumSize(boundingRect().size());
    setMaximumSize(boundingRect().size());
    setZValue(120);
}

void GamePanelButton::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    Q_UNUSED(widget);
    bool down = false;
    if (m_canToggle)
    {
        down = m_isToggled;
    }
    else
    {
        down = option->state & QStyle::State_Sunken;
    }
    painter->save();
    painter->setRenderHint(QPainter::Antialiasing, true);
    // draw button
    QBrush brush(painter->brush());
    QColor cColor;

    if (down)
    {
        // clicked state
        cColor = QColor(255,0,0);
    }
    else if (m_hovered)
    {
        //mouse hovered state
        cColor = QColor(0,0,255);
    }
    else
    {
        //default state
        cColor = QColor(0,255,0);
    }

    brush.setColor(cColor);

    brush.setStyle(Qt::SolidPattern);
    QPen pen(painter->pen());

    pen.setColor(cColor);

    painter->setBrush(brush);
    painter->setPen(pen);
    painter->drawRoundedRect(3, 3, 64, 64, 2, 2, Qt::AbsoluteSize);
    painter->drawPixmap(11, 11, 48, 48, m_pixmap);

    painter->restore();
}

QRectF GamePanelButton::boundingRect() const
{
    return QRectF(0, 0, 70, 70);
}

void GamePanelButton::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)
    {
        if (m_canToggle)
        {
            m_isToggled = !m_isToggled;
            emit toggled(!m_isToggled);
        }
        else
        {
            emit pressed();
        }
        update();
        event->accept();
    }
    else if (event->button() == Qt::RightButton)
    {
        emit rightClicked();
        event->accept();
    }
}

void GamePanelButton::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
    update();
}

void GamePanelButton::setToggled(bool value)
{
    if (value != m_isToggled)
    {
        m_isToggled = value;
        update();
    }
}

void GamePanelButton::hoverEnterEvent(QGraphicsSceneHoverEvent *event)
{
    m_hovered = true;
    update();
}

void GamePanelButton::hoverLeaveEvent(QGraphicsSceneHoverEvent *event)
{
    m_hovered = false;
    update();
}
